//
//  MainViewController.m
//  汽车大灯色温蓝牙
//
//  Created by dfwx on 2020/9/5.
//  Copyright © 2020 zhongdaodianzi. All rights reserved.
//

#import "MainViewController.h"
#import "HomeView.h"
#import "SceneView.h"
#import "AutoAlertView.h"
#import "DropTableView.h"
#import <CoreLocation/CoreLocation.h>
#import <CoreBluetooth/CoreBluetooth.h>
#import "BlueToothListView.h"
#import "PasswordView.h"
#import "DataModel.h"
#import "DayLightAlertView.h"


@interface MainViewController () <CLLocationManagerDelegate, CBCentralManagerDelegate, CBPeripheralDelegate, HomeViewDelegate, BlueToothListViewDelegate, SceneViewDelegate, DropTableViewDelegate, AutoAlertViewDelegate, DayLightAlertViewDelegate>

{

    

}
@property (weak, nonatomic) IBOutlet UIView *contentView;
@property (weak, nonatomic) IBOutlet UIButton *homeButton;
@property (weak, nonatomic) IBOutlet UIButton *sceneButton;
@property (weak, nonatomic) IBOutlet UIButton *listButton;

@property (nonatomic, assign) BOOL isHome;// Yes Home/No  scene
@property (nonatomic, strong) HomeView *homeView;
@property (nonatomic, strong) SceneView *sceneView;

@property (nonatomic, strong) CBCentralManager *centerManager;
@property (nonatomic, strong) CBPeripheral *leftPeripheral;
@property (nonatomic, strong) CBPeripheral *rightPeripheral;
@property (nonatomic, strong) CBCharacteristic *leftCharacteristic;
@property (nonatomic, strong) CBCharacteristic *rightCharacteristic;
@property (nonatomic, strong) NSMutableArray *peripheralArray;
@property (nonatomic, strong) NSMutableArray *connectPeripheralArray;
@property (nonatomic, strong) BlueToothListView *blueView;

@property (nonatomic, strong) NSMutableDictionary *macDictionary;
@property (nonatomic, strong) DataModel *model;
@property (weak, nonatomic) IBOutlet UILabel *titleLabel;
@property (weak, nonatomic) IBOutlet UIView *backView;
@property (nonatomic, assign) NSInteger number;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *backTop;
@property (nonatomic, assign) BOOL isAutoConnected;
@property (nonatomic, assign) BOOL isAutoRightConnect;
@property (nonatomic, strong) NSString *leftPassword;
@property (nonatomic, strong) NSString *rightPassword;
@property (nonatomic, assign) BOOL isUpdateAction;

@property (nonatomic, assign) BOOL isLearn;
@property (nonatomic, strong) NSTimer *learnTimer;

@property (nonatomic, assign) NSInteger isControlType;// 操作控件的类型,1/圆  2/ 滑动条  其他是模式
@property (nonatomic, strong) NSMutableDictionary *searchMacDic;
@property (nonatomic, assign) BOOL canWriteLeftCommand;
@property (nonatomic, assign) BOOL canWriteRightCommand;

@property (nonatomic, assign) BOOL isLock;
@property (nonatomic, strong) NSString *city;
@property (nonatomic, strong) NSMutableArray *testArray;
@property (nonatomic, strong) CLLocationManager*locationmanager;//定位服务

@property (nonatomic, assign) CGFloat latitude;//经度

@property (nonatomic, assign) CGFloat longitude;//纬度


@end

@implementation MainViewController

- (NSMutableArray *)testArray {
    if (!_testArray) {
        _testArray = [NSMutableArray array];
    }
    return _testArray;
}

- (NSMutableDictionary *)searchMacDic {
    
    if (!_searchMacDic) {
        _searchMacDic = [NSMutableDictionary dictionary];
    }
    return _searchMacDic;
}

#pragma mark - viewDidload

- (void)viewDidLoad {
    [super viewDidLoad];
    self.titleLabel.text = WWNSLocalizedString(@"HomeTitle",@"123");
    [UIApplication sharedApplication].statusBarHidden = YES;
    self.canWriteLeftCommand = NO;
    self.canWriteRightCommand = NO;
    self.isLearn = NO;
    self.isUpdateAction = YES;
    self.isAutoConnected = YES;
    self.isAutoRightConnect = YES;
    self.leftPassword = [self getLeftPeropheralPassword];
    self.rightPassword = [self getRightPeropheralPassword];
    self.isHome = YES;
    self.number = 0;
    self.isLock = NO;
    NSArray * fontArrays = [[NSArray alloc] initWithArray:[UIFont familyNames]];
    for (NSString * temp in fontArrays) {
        NSLog(@"Font name  = %@", temp);
    }
    self.titleLabel.font = [UIFont fontWithName:@"FZXiHei I-Z08S" size:18];
    self.homeButton.titleLabel.font = [UIFont fontWithName:@"FZXiHei I-Z08S" size:15];
    self.sceneButton.titleLabel.font = [UIFont fontWithName:@"FZXiHei I-Z08S" size:15];
    
    [self initCenterManager];
    [self addHomeView];
    [self addSceneView];
    [self startLocation];
    [self addBlueListView];
    // Do any additional setup after loading the view from its nib.
}



- (void)viewWillAppear:(BOOL)animated {
    
    [super viewWillAppear:YES];
    [self.navigationController setNavigationBarHidden:YES];
    
}

- (void)viewDidLayoutSubviews {
    
    [super viewDidLayoutSubviews];
    self.number ++;
    NSLog(@"%@",self.backView);
    if (self.backView.frame.origin.y < 20) {
        self.backTop.constant = 20;
    }
}


#pragma mark - private

- (void)initCenterManager {
    
    self.model = [[DataModel alloc]init];
    self.centerManager = [[CBCentralManager alloc]initWithDelegate:self queue:nil];
}

- (void)addHomeView {
    
    self.homeView = [[[NSBundle mainBundle]loadNibNamed:@"HomeView" owner:nil options:nil]lastObject];
    self.homeView.hidden = !self.isHome;
    self.homeView.delegate = self;
    [self.contentView addSubview:self.homeView];
    [self.homeView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(0);
        make.right.mas_equalTo(0);
        make.bottom.mas_equalTo(0);
        make.top.mas_equalTo(0);
    }];
    
    
}

- (void)addBlueListView {
    
    self.blueView = [[[NSBundle mainBundle]loadNibNamed:NSStringFromClass([BlueToothListView class]) owner:nil options:nil]lastObject];
    self.blueView.frame = [NSObject mainWindow].bounds;
    self.blueView.hidden = YES;
    self.blueView.delegate = self;
    [[NSObject mainWindow]addSubview:self.blueView];
}

- (void)addDayLightAlertViewAction {
    
    DayLightAlertView *alertView = [[[NSBundle mainBundle]loadNibNamed:NSStringFromClass([DayLightAlertView class]) owner:nil options:nil]lastObject];
    alertView.frame = [NSObject mainWindow].bounds;
    alertView.delegate = self;
    alertView.tag = 77777;
    [[NSObject mainWindow]addSubview:alertView];
    
    [NSTimer scheduledTimerWithTimeInterval:3 repeats:NO block:^(NSTimer * _Nonnull timer) {
        DayLightAlertView *alertView = [[NSObject mainWindow]viewWithTag:77777];
        if (alertView) {
            if (alertView.selectButton.selected) {
                [[NSUserDefaults standardUserDefaults]setObject:@"no" forKey:noLonger_show_key];
            }
            [alertView removeFromSuperview];
        }
    }];

}

- (void)addSceneView {
    
    self.sceneView = [[[NSBundle mainBundle]loadNibNamed:@"SceneView" owner:nil options:nil]lastObject];
    self.sceneView.hidden = self.isHome;
    self.sceneView.delegate = self;
    [self.contentView addSubview:self.sceneView];
    [self.sceneView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(0);
        make.right.mas_equalTo(0);
        make.bottom.mas_equalTo(0);
        make.top.mas_equalTo(0);
    }];

    
}

- (NSString *)getLeftPeropheralName {
    
    NSString *name = [[NSUserDefaults standardUserDefaults]objectForKey:left_peripheral_name];
    return name;
}

- (NSString *)getRightPeropheralName {
    
    NSString *name = [[NSUserDefaults standardUserDefaults]objectForKey:right_peripheral_name];
    return name;
}

- (NSString *)getLeftPeropheralPassword {
    
    NSString *password = [[NSUserDefaults standardUserDefaults]objectForKey:left_peripheral_password];
    return password;
}

- (NSString *)getRightPeropheralPassword {
    
    NSString *password = [[NSUserDefaults standardUserDefaults]objectForKey:right_peripheral_password];
    return password;
}

- (NSString *)getLeftPeripheralData {
    
    NSString *hex = [[NSUserDefaults standardUserDefaults]objectForKey:left_peripheral_learn_data];
    return hex;
}

- (NSString *)getRightPeripheralData {
    
    NSString *hex = [[NSUserDefaults standardUserDefaults]objectForKey:right_peripheral_learn_data];
    return hex;
}

- (void)saveLeftPeripheralWithName:(NSString *)name {
    
    [[NSUserDefaults standardUserDefaults]setObject:name forKey:left_peripheral_name];
    [[NSUserDefaults standardUserDefaults]synchronize];
}

- (void)saveRightPeripheralWithName:(NSString *)name {
    
    [[NSUserDefaults standardUserDefaults]setObject:name forKey:right_peripheral_name];
    [[NSUserDefaults standardUserDefaults]synchronize];
}

- (void)saveLeftPeripheralWithPassword:(NSString *)password {
    
    [[NSUserDefaults standardUserDefaults]setObject:password forKey:left_peripheral_password];
    [[NSUserDefaults standardUserDefaults]synchronize];
}

- (void)saveRightPeripheralWithPassword:(NSString *)password {
    
    [[NSUserDefaults standardUserDefaults]setObject:password forKey:right_peripheral_password];
    [[NSUserDefaults standardUserDefaults]synchronize];
}

- (void)saveLeftPeripheralWithData:(NSString *)data {
    
    [[NSUserDefaults standardUserDefaults]setObject:data forKey:left_peripheral_learn_data];
    [[NSUserDefaults standardUserDefaults]synchronize];
}

- (void)saveRightPeripheralWithData:(NSString *)data {
    
    [[NSUserDefaults standardUserDefaults]setObject:data forKey:right_peripheral_learn_data];
    [[NSUserDefaults standardUserDefaults]synchronize];
}



#pragma mark - action

- (IBAction)homeButtonClicked:(UIButton *)sender {
    self.isHome = !self.isHome;
}

- (IBAction)sceneButtonClicked:(UIButton *)sender {
    self.isHome = NO;
}


- (IBAction)backButtonClicked:(UIButton *)sender {
        self.isHome = YES;
    
}

- (void)blueListViewShow {
    [self.centerManager scanForPeripheralsWithServices:nil options:nil];
    self.blueView.hidden = NO;
    self.blueView.scanButton.selected = YES;
    
}

- (IBAction)listButtonClicked:(UIButton *)sender {
    
//    CGPoint point = [sender convertPoint:CGPointMake(0, 0) toView:[NSObject mainWindow]];
    CGRect rect = [sender convertRect:sender.bounds toView:[NSObject mainWindow]];
    DropTableView *dropView = [[DropTableView alloc]initWithFrame:[NSObject mainWindow].bounds];
    dropView.locationRect = rect;
    dropView.delegate = self;
    [[NSObject mainWindow]insertSubview:dropView belowSubview:self.blueView];
    NSLog(@"%f,%f,%f,%f",rect.origin.x,rect.origin.y,rect.size.width,rect.size.height);
}


#pragma mark - 定位
//开始定位
-(void) startLocation
{
    //判断定位功能是否打开
    
    dispatch_async(dispatch_get_main_queue(), ^{
        if ([CLLocationManager locationServicesEnabled]) {
            self.locationmanager = [[CLLocationManager alloc]init];
            self.locationmanager.delegate = self;
            [self.locationmanager requestAlwaysAuthorization];
            [self.locationmanager requestWhenInUseAuthorization];
            
            //设置寻址精度
            self.locationmanager.desiredAccuracy = kCLLocationAccuracyBest;
            self.locationmanager.distanceFilter = 5.0;
            [self.locationmanager startUpdatingLocation];
        }else {
            
            [self showHUDWith:@"请允许使用你的定位功能进行获取天气情况"];
        }
    });
    
}

#pragma mark 定位成功后则执行此代理方法
-(void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray<CLLocation *> *)locations
{
    [self.locationmanager stopUpdatingHeading];
    [self.locationmanager stopUpdatingLocation];
    //旧址
    CLLocation *currentLocation = [locations lastObject];
    CLGeocoder *geoCoder = [[CLGeocoder alloc]init];
    //打印当前的经度与纬度
    NSLog(@"%f,%f",currentLocation.coordinate.latitude,currentLocation.coordinate.longitude);
    self.latitude = currentLocation.coordinate.latitude;
    self.longitude = currentLocation.coordinate.longitude;
    
    
    //反地理编码
    [geoCoder reverseGeocodeLocation:currentLocation completionHandler:^(NSArray<CLPlacemark *> * _Nullable placemarks, NSError * _Nullable error)
    {
        NSLog(@"反地理编码");
        NSLog(@"反地理编码%ld",placemarks.count);
        if (placemarks.count > 0) {
            CLPlacemark *placeMark = placemarks[0];
            NSString *city = placeMark.locality;
            if (!city) {
                city = @"无法定位当前城市";
            }
            
            self.city = city;
            /*看需求定义一个全局变量来接收赋值*/
            NSLog(@"城市----%@",placeMark.country);//当前国家
            NSLog(@"城市%@",city);//当前的城市
            NSLog(@"%@",placeMark.subLocality);//当前的位置
            NSLog(@"%@",placeMark.thoroughfare);//当前街道
            NSLog(@"%@",placeMark.name);//具体地址
//            [locationmanager stopUpdatingLocation];
            
        }
        [self fetchWeaTherApi];

    }];
    
}

#pragma mark CoreLocation delegate (定位失败)
//定位失败后调用此代理方法
-(void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error
{
    //设置提示提醒用户打开定位服务
//    UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"允许定位提示" message:@"请在设置中打开定位" preferredStyle:UIAlertControllerStyleAlert];
//    UIAlertAction *okAction = [UIAlertAction actionWithTitle:@"打开定位" style:UIAlertActionStyleDefault handler:nil];
//    
//    UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil];
//    [alert addAction:okAction];
//    [alert addAction:cancelAction];
//    [self presentViewController:alert animated:YES completion:nil];
}



- (void)fetchWeaTherApi {
    
    // https://api.seniverse.com/v3/weather/now.json?key=SAUbg5V2WEAoPatDh&location=beijing&language=zh-Hans&unit=c
    
    NSString *url = @"https://api.seniverse.com/v3/weather/now.json";
//    NSString *url = @"https://api.thinkpage.cn/v3/weather/now.json?key=boarngyp3kmsnulj";
    AFHTTPSessionManager *session = [AFHTTPSessionManager manager];
    NSUserDefaults  *defaults = [ NSUserDefaults  standardUserDefaults];
    // 取得 iPhone 支持的所有语言设置
    NSArray*languages = [NSLocale preferredLanguages];
    NSLog(@"%@",languages);
    NSString *language = @"";
//    NSDictionary *params = @{@"location":[NSString stringWithFormat:@"%f:%f",latitude,longitude],};
    NSDictionary *params = @{@"key":@"djdm8ik3o5y4c30m",@"location":self.city,@"language":@"zh-Hans",@"unit":@"c"};

    [session GET:url parameters:params progress:^(NSProgress * _Nonnull downloadProgress) {
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSLog(@"%@",responseObject);
        NSArray *arry = responseObject[@"results"];
        if (arry.count > 0) {
            NSDictionary *firstDic = [arry firstObject];
            NSString *code = [NSString stringWithFormat:@"%@",firstDic[@"now"][@"code"]];
            NSString *text = [self weatherCodeToName:code];

            NSString *temperature = [NSString stringWithFormat:@"%@",firstDic[@"now"][@"temperature"]];
            self.homeView.weatherNameLabel.text = [NSString stringWithFormat:@"%@\n%@℃\n%@",text,temperature,self.city];
            self.homeView.weatherIconImageView.image = [UIImage imageNamed:code];
//            NSLog(@"天气:%@,code:%@,温度:%°C",text,code,temperature);
            if (self.connectPeripheralArray.count > 0) {
                /*
                 @{@"name":@"晴天",@"white":@"100",@"yellow":@"0",@"bright":@"20",@"default":@"scene_01_default",@"select":@"scene_01_click"},    @{@"name":@"夜间",@"white":@"100",@"yellow":@"0",@"bright":@"100",@"default":@"scene_02_default",@"select":@"scene_02_click"},    @{@"name":@"多云",@"white":@"90",@"yellow":@"10",@"bright":@"100",@"default":@"scene_03_default",@"select":@"scene_03_click"},    @{@"name":@"小雨",@"white":@"80",@"yellow":@"20",@"bright":@"100",@"default":@"scene_04_default",@"select":@"scene_04_click"},    @{@"name":@"中雨",@"white":@"70",@"yellow":@"30",@"bright":@"100",@"default":@"scene_05_default",@"select":@"scene_05_click"},    @{@"name":@"大雨",@"white":@"60",@"yellow":@"50",@"bright":@"100",@"default":@"scene_06_default",@"select":@"scene_06_click"},    @{@"name":@"小雪",@"white":@"50",@"yellow":@"50",@"bright":@"100",@"default":@"scene_07_default",@"select":@"scene_07_click"},    @{@"name":@"中雪",@"white":@"40",@"yellow":@"60",@"bright":@"100",@"default":@"scene_08_default",@"select":@"scene_08_click"},    @{@"name":@"大雪",@"white":@"30",@"yellow":@"70",@"bright":@"100",@"default":@"scene_09_default",@"select":@"scene_09_click"},    @{@"name":@"雷雨",@"white":@"20",@"yellow":@"80",@"bright":@"100",@"default":@"scene_10_default",@"select":@"scene_10_click"},    @{@"name":@"小雾",@"white":@"10",@"yellow":@"90",@"bright":@"100",@"default":@"scene_11_default",@"select":@"scene_11_click"},    @{@"name":@"大雾",@"white":@"0",@"yellow":@"100",@"bright":@"100",@"default":@"scene_12_default",@"select":@"scene_12_click"}
                 **/
                
                [self setLightFormWeatherWithCode:code];
                
            }

        }
        NSLog(@"请求成功%@",arry);

    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        NSLog(@"请求失败%@",error);
    }];
    
    
}

- (NSString *)weatherCodeToImageName:(NSString *)code {
    if (code.intValue < 4) {
        // 晴天
        return WWNSLocalizedString(@"SunnyDay", @"晴天");
        
    }else if (code.intValue == 4 || code.intValue == 5 || code.intValue == 6) {
        
        // 多云
        return WWNSLocalizedString(@"AtNight", @"夜间");
    }else if (code.intValue == 7 || code.intValue == 8 || code.intValue == 9 || code.intValue == 38) {
        
        // 多云
        return WWNSLocalizedString(@"cloudy", @"多云");
    }else if (code.intValue == 10 || code.intValue == 13 || code.intValue == 32 || code.intValue == 33) {
        // 小雨
        return WWNSLocalizedString(@"LightRain", @"小雨");
    }else if (code.intValue == 14) {
        // 中雨
        return WWNSLocalizedString(@"ModerateRain", @"中雨");
    }else if (code.intValue == 15) {
        // 大雨
        return WWNSLocalizedString(@"HeavyRain", @"大雨");
    }else if (code.intValue == 20 || code.intValue == 21 || code.intValue == 22 || code.intValue == 99) {
        // 小雪
        return WWNSLocalizedString(@"LightSnow", @"小雪");
    }else if (code.intValue == 23) {
        // 中雪
        return WWNSLocalizedString(@"ModerateSnow", @"中雪");
    }else if (code.intValue == 24) {
        // 大雪
        return WWNSLocalizedString(@"HeavySnow", @"大雪");
    }else if (code.intValue == 11 || code.intValue == 12) {
        // 雷雨
        return WWNSLocalizedString(@"Thunderstorm", @"雷雨");
    }else if (code.intValue == 30) {
        // 小雾
        return WWNSLocalizedString(@"Mist", @"小雾");
    }else{
        // 雷雨
        return WWNSLocalizedString(@"DenseFog", @"雷雨");
    }
    
}

- (NSString *)weatherCodeToName:(NSString *)code {
    if (code.intValue < 4) {
        // 晴天
        return WWNSLocalizedString(@"SunnyDay", @"晴天");
        
    }else if (code.intValue == 4 || code.intValue == 5 || code.intValue == 6) {
        
        // 多云
        return WWNSLocalizedString(@"AtNight", @"夜间");
    }else if (code.intValue == 7 || code.intValue == 8 || code.intValue == 9 || code.intValue == 38) {
        
        // 多云
        return WWNSLocalizedString(@"cloudy", @"多云");
    }else if (code.intValue == 10 || code.intValue == 13 || code.intValue == 32 || code.intValue == 33) {
        // 小雨
        return WWNSLocalizedString(@"LightRain", @"小雨");
    }else if (code.intValue == 14) {
        // 中雨
        return WWNSLocalizedString(@"ModerateRain", @"中雨");
    }else if (code.intValue == 15) {
        // 大雨
        return WWNSLocalizedString(@"HeavyRain", @"大雨");
    }else if (code.intValue == 20 || code.intValue == 21 || code.intValue == 22 || code.intValue == 99) {
        // 小雪
        return WWNSLocalizedString(@"LightSnow", @"小雪");
    }else if (code.intValue == 23) {
        // 中雪
        return WWNSLocalizedString(@"ModerateSnow", @"中雪");
    }else if (code.intValue == 24) {
        // 大雪
        return WWNSLocalizedString(@"HeavySnow", @"大雪");
    }else if (code.intValue == 11 || code.intValue == 12) {
        // 雷雨
        return WWNSLocalizedString(@"Thunderstorm", @"雷雨");
    }else if (code.intValue == 30) {
        // 小雾
        return WWNSLocalizedString(@"Mist", @"小雾");
    }else{
        // 雷雨
        return WWNSLocalizedString(@"DenseFog", @"雷雨");
    }
    
}

- (void)setLightFormWeatherWithCode:(NSString *)code {
    
//    NSArray *array = @[
//        @{@"name":@"晴天",@"white":@"100",@"yellow":@"0",@"bright":@"20",@"default":@"scene_01_default",@"select":@"scene_01_click",@"code":@"0"},
//        @{@"name":@"夜间",@"white":@"100",@"yellow":@"0",@"bright":@"100",@"default":@"scene_02_default",@"select":@"scene_02_click",@"code":@"100"},
//        @{@"name":@"多云",@"white":@"90",@"yellow":@"10",@"bright":@"100",@"default":@"scene_03_default",@"select":@"scene_03_click",@"code":@"4"},
//        @{@"name":@"小雨",@"white":@"80",@"yellow":@"20",@"bright":@"100",@"default":@"scene_04_default",@"select":@"scene_04_click"},
//        @{@"name":@"中雨",@"white":@"70",@"yellow":@"30",@"bright":@"100",@"default":@"scene_05_default",@"select":@"scene_05_click"},
//        @{@"name":@"大雨",@"white":@"60",@"yellow":@"50",@"bright":@"100",@"default":@"scene_06_default",@"select":@"scene_06_click"},
//        @{@"name":@"小雪",@"white":@"50",@"yellow":@"50",@"bright":@"100",@"default":@"scene_07_default",@"select":@"scene_07_click"},
//        @{@"name":@"中雪",@"white":@"40",@"yellow":@"60",@"bright":@"100",@"default":@"scene_08_default",@"select":@"scene_08_click"},
//        @{@"name":@"大雪",@"white":@"30",@"yellow":@"70",@"bright":@"100",@"default":@"scene_09_default",@"select":@"scene_09_click"},
//        @{@"name":@"雷雨",@"white":@"20",@"yellow":@"80",@"bright":@"100",@"default":@"scene_10_default",@"select":@"scene_10_click"},
//        @{@"name":@"小雾",@"white":@"10",@"yellow":@"90",@"bright":@"100",@"default":@"scene_11_default",@"select":@"scene_11_click"},
//        @{@"name":@"大雾",@"white":@"0",@"yellow":@"100",@"bright":@"100",@"default":@"scene_12_default",@"select":@"scene_12_click"}
//    ];
//
    CGFloat bright = 255;
    NSInteger yellow = bright;
    NSInteger white = bright - yellow;
    
    
    
    if (code.intValue < 4) {
        // 晴天
        bright = 128;
        white = bright *1;
        yellow = bright -white;
        
    }else if (code.intValue == 4 || code.intValue == 5 || code.intValue == 6) {
        
        // 多云
        white = bright *0.9;
        yellow = bright -white;
    }else if (code.intValue == 7 || code.intValue == 8 || code.intValue == 9 || code.intValue == 38) {
        
        // 多云
        white = bright;
        yellow = bright -white;
    }else if (code.intValue == 10 || code.intValue == 13 || code.intValue == 32 || code.intValue == 33) {
        // 小雨
        white = bright *0.8;
        yellow = bright -white;
    }else if (code.intValue == 14) {
        // 中雨
        white = bright *0.7;
        yellow = bright -white;
    }else if (code.intValue == 15) {
        // 大雨
        white = bright *0.6;
        yellow = bright -white;
    }else if (code.intValue == 20 || code.intValue == 21 || code.intValue == 22 || code.intValue == 99) {
        // 小雪
        white = bright *0.5;
        yellow = bright -white;
    }else if (code.intValue == 23) {
        // 中雪
        white = bright *0.4;
        yellow = bright -white;
    }else if (code.intValue == 24) {
        // 大雪
        white = bright *0.3;
        yellow = bright -white;
    }else if (code.intValue == 11 || code.intValue == 12) {
        // 雷雨
        white = bright *0.2;
        yellow = bright -white;
    }else if (code.intValue == 30) {
        // 小雾
        white = bright *0.1;
        yellow = bright -white;
    }else{
        // 雷雨
        white = bright *0;
        yellow = bright -white;
    }
    self.isControlType = 0;

    NSInteger birghtPrecent = bright/255.0 *100;
    NSString *whiteString = [NSString stringWithFormat:@"%ld",white];
    NSString *yellowString = [NSString stringWithFormat:@"%ld",yellow];
    NSString *brightString = [NSString stringWithFormat:@"%ld",birghtPrecent];
    NSString *commandString = [NSString stringWithFormat:@"a0%@%@%@000000",[whiteString ConvertedDecimalStringToHexdecimalString],[yellowString ConvertedDecimalStringToHexdecimalString],[brightString ConvertedDecimalStringToHexdecimalString]];
    
    for (CBPeripheral *peripheral in self.connectPeripheralArray) {
        if ([peripheral isEqual:self.leftPeripheral]) {
            [self sendCommandWith:self.leftPeripheral withCharacteristic:self.leftCharacteristic withCommand:commandString];

        }
        
        if ([peripheral isEqual:self.rightPeripheral]) {
            [self sendCommandWith:self.rightPeripheral withCharacteristic:self.rightCharacteristic withCommand:commandString];

        }
    }
}

#pragma mark - blueToothDelegate

#pragma mark - CBCenteralManagerDelegate
-(void)centralManagerDidUpdateState:(CBCentralManager *)central{
    switch (central.state) {
        case CBManagerStateUnknown:{
            [self showHUDWith:@"请确保手机蓝牙已经打开"];
        }
            break;
        case CBManagerStatePoweredOn:{
            [self.centerManager scanForPeripheralsWithServices:nil options:nil];

//            [self.centerManager scanForPeripheralsWithServices:nil options:nil];
        }
            break;
        case CBManagerStateResetting:{
            [self showHUDWith:@"The connection with the system service was momentarily lost, update imminent."];
        }
            break;
        case CBManagerStatePoweredOff:{
            [self showHUDWith:@"蓝牙处于关闭状态，请将蓝牙开启"];
        }
            break;
        case CBManagerStateUnsupported:{
            [self showHUDWith:@"蓝牙不支持"];
        }
            break;
        case CBManagerStateUnauthorized:{
            [self showHUDWith:@"无法认证蓝牙"];
        }
            break;
        default:
            break;
    }
}

#pragma mark - 搜索发现周边蓝牙
-(void)centralManager:(CBCentralManager *)central didDiscoverPeripheral:(CBPeripheral *)peripheral advertisementData:(NSDictionary<NSString *,id> *)advertisementData RSSI:(NSNumber *)RSSI{
    if (peripheral.name.length > 0) {
        if (![self.testArray containsObject:peripheral]) {
            [self.testArray addObject:peripheral];
            NSLog(@"正在搜索蓝牙......%@",peripheral);

        }
    }
    
    NSData *advDataManufacturerData = advertisementData[@"kCBAdvDataManufacturerData"];
    NSString *macString = [advDataManufacturerData convertDataToHexStr];
    
    if (macString.length > 0) {
        NSString *bleVersion = [macString subStringWithRangeForNil:NSMakeRange(10, 2)];
        if (bleVersion.length > 0) {
            [self.searchMacDic setObject:bleVersion forKey:peripheral.name];
        }
    }
    
    NSRange range = [peripheral.name rangeOfString:@"Smart travel"];
    if (![self.peripheralArray containsObject:peripheral] && range.length > 0) {
        [self.peripheralArray addObject:peripheral];
        self.blueView.dataArray = self.peripheralArray;
        NSLog(@"正在搜索蓝牙......%@\n%@",peripheral,advertisementData);
        NSData *advDataManufacturerData = advertisementData[@"kCBAdvDataManufacturerData"];
        NSString *macString = [advDataManufacturerData convertDataToHexStr];
        [self.macDictionary setObject:peripheral forKey:macString];
        NSLog(@"%@",self.macDictionary);


        
    }
    
    if (self.isAutoConnected == YES) {
        if ([peripheral.name isEqualToString:[self getLeftPeropheralName]]) {
            [self.centerManager connectPeripheral:peripheral options:nil];
        }
        
    }
    
    if (self.isAutoRightConnect == YES) {
        
        if ([peripheral.name isEqualToString:[self getRightPeropheralName]]) {
            [self.centerManager connectPeripheral:peripheral options:nil];
        }
    }
    
    
}
#pragma mark - 蓝牙连接回调
-(void)centralManager:(CBCentralManager *)central didConnectPeripheral:(CBPeripheral *)peripheral{
    NSLog(@"%@蓝牙连接成功",peripheral.name);
    peripheral.delegate = self;
    if (![self.connectPeripheralArray containsObject:peripheral]) {
        [self.connectPeripheralArray addObject:peripheral];
        if ([self.peripheralArray containsObject:peripheral]) {
            [self.peripheralArray removeObject:peripheral];

        }
        self.blueView.dataArray = self.peripheralArray;
        self.blueView.connectArray = self.connectPeripheralArray;

    }
    
    if ([peripheral.name isEqualToString:[self getLeftPeropheralName]]) {
        self.leftPeripheral = peripheral;
//        self.isAutoConnected ++;
    }else if ([peripheral.name isEqualToString:[self getRightPeropheralName]]) {
        self.rightPeripheral = peripheral;
//        self.isAutoRightConnect ++;
    }else {
//        if (self.leftPeripheral == nil && self.rightPeripheral == nil) {
            
            if ([self getLeftPeropheralName].length > 0 && [self getRightPeropheralName].length > 0) {
                if (self.rightPeripheral == nil && self.leftPeripheral) {
                    
                    self.rightPeripheral = peripheral;
                }else {
                    self.leftPeripheral = peripheral;
                }
            }else if ([self getLeftPeropheralName].length > 0 && [self getRightPeropheralName].length == 0) {
                if (self.rightPeripheral == nil && self.leftPeripheral) {
                    
                    self.rightPeripheral = peripheral;
                }else {
                    self.leftPeripheral = peripheral;
                }
                
            }else if ([self getLeftPeropheralName].length == 0 && [self getRightPeropheralName].length > 0) {
                if (self.rightPeripheral == nil && self.leftPeripheral) {
                    
                    self.rightPeripheral = peripheral;
                }else {
                    self.leftPeripheral = peripheral;
                }
                
            }else {
                
                if (self.rightPeripheral == nil && self.leftPeripheral) {
                    
                    self.rightPeripheral = peripheral;
                }else {
                    self.leftPeripheral = peripheral;
                }

            }
//            self.isAutoConnected ++;
        
//        }else if (self.leftPeripheral && self.rightPeripheral == nil) {
//            self.rightPeripheral = peripheral;
//            self.isAutoRightConnect ++;
//        }else if (self.rightPeripheral && self.leftPeripheral == nil) {
//            self.leftPeripheral = peripheral;
//            self.isAutoConnected ++;
//        }
        
    }
    
    
    
    [peripheral discoverServices:nil];

}
#pragma mark - 蓝牙断开回调
-(void)centralManager:(CBCentralManager *)central didDisconnectPeripheral:(CBPeripheral *)peripheral error:(NSError *)error{
    NSLog(@"%@蓝牙断开",peripheral.name);
    if ([peripheral isEqual:self.leftPeripheral]) {
        self.homeView.topLeftButton.selected = YES;
        self.canWriteLeftCommand = NO;
    }
    
    if ([peripheral isEqual:self.rightPeripheral]) {
        self.homeView.topRightButton.selected = YES;
        self.canWriteRightCommand = NO;
    }
    if ([peripheral isEqual:self.leftPeripheral]) {
        self.leftPeripheral = nil;
        self.leftCharacteristic = nil;
    }
    
    if ([peripheral isEqual:self.rightPeripheral]) {
        self.rightPeripheral = nil;
        self.rightCharacteristic = nil;
    }
    if ([self.connectPeripheralArray containsObject:peripheral]) {
        [self.connectPeripheralArray removeObject:peripheral];
        self.blueView.connectArray = self.connectPeripheralArray;
        
        
    }
    
    [self.centerManager scanForPeripheralsWithServices:nil options:nil];
//    [self.centerManager connectPeripheral:peripheral options:nil];


}


#pragma mark - 发现服务
-(void)peripheral:(CBPeripheral *)peripheral didDiscoverServices:(NSError *)error{
    for (CBService *service in peripheral.services) {
        NSLog(@"服务:%@\n",service);
        [peripheral discoverCharacteristics:nil forService:service];
    }
}
#pragma mark - 发现服务特征
-(void)peripheral:(CBPeripheral *)peripheral didDiscoverCharacteristicsForService:(CBService *)service error:(NSError *)error{
    NSLog(@"%@",service.characteristics);

    if ([service.UUID.UUIDString isEqualToString:@"FFF0"]) {
        NSLog(@"%@",service.characteristics);
        for (CBCharacteristic *characteristic in service.characteristics) {
            NSLog(@"特征:%@\n",characteristic);
            [peripheral setNotifyValue:YES forCharacteristic:characteristic];

            if ([characteristic.UUID.UUIDString isEqualToString:@"FFF1"]) {
                if ([peripheral isEqual:self.leftPeripheral]) {

                    self.leftCharacteristic = characteristic;
//                    [self.leftPeripheral writeValue:[@"C6000000000000" convertHexStrToData] forCharacteristic:self.leftCharacteristic type:CBCharacteristicWriteWithResponse];

                    NSLog(@"%@",[self getLeftPeropheralName]);
                    if ([peripheral.name isEqualToString:[self getLeftPeropheralName]]) {
                        NSString *password = [self getLeftPeropheralPassword];
                        NSString *hexString = @"";
                        for (NSInteger i = 0; i < password.length; i ++) {
                            NSString *temp = [password substringWithRange:NSMakeRange(i, 1)];
                            hexString = [NSString stringWithFormat:@"%@%@",hexString,[temp ConvertedDecimalStringToHexdecimalString]];
                        }
                        NSLog(@"发送密码:%@",[NSString stringWithFormat:@"C4%@",hexString]);
                        

                        [self.leftPeripheral writeValue:[[NSString stringWithFormat:@"C4%@",hexString] convertHexStrToData] forCharacteristic:self.leftCharacteristic type:CBCharacteristicWriteWithResponse];
                    }else {
                        NSLog(@"发送密码1:C4060606060606");
                        self.leftPassword = @"666666";

                        [self.leftPeripheral writeValue:[@"C4060606060606" convertHexStrToData] forCharacteristic:self.leftCharacteristic type:CBCharacteristicWriteWithResponse];
                        
                    }
                    
                }else {
                    self.rightCharacteristic = characteristic;
//                    [self.rightPeripheral writeValue:[@"C6000000000000" convertHexStrToData] forCharacteristic:self.rightCharacteristic type:CBCharacteristicWriteWithResponse];

                    if ([peripheral.name isEqualToString:[self getRightPeropheralName]]) {
                        NSString *password = [self getRightPeropheralPassword];
                        NSString *hexString = @"";
                        for (NSInteger i = 0; i < password.length; i ++) {
                            NSString *temp = [password substringWithRange:NSMakeRange(i, 1)];
                            hexString = [NSString stringWithFormat:@"%@%@",hexString,[temp ConvertedDecimalStringToHexdecimalString]];
                        }
                        NSLog(@"发送密码:%@",[NSString stringWithFormat:@"C4%@",hexString]);
                        [self.rightPeripheral writeValue:[[NSString stringWithFormat:@"C4%@",hexString] convertHexStrToData] forCharacteristic:self.rightCharacteristic type:CBCharacteristicWriteWithResponse];
                    }else {
                        NSLog(@"发送密码1:C4060606060606");
                        self.rightPassword = @"666666";

                        [self.rightPeripheral writeValue:[@"C4060606060606" convertHexStrToData] forCharacteristic:self.rightCharacteristic type:CBCharacteristicWriteWithResponse];

                    }
                    
                }


            }

        }
        
        
    }
    
}


#pragma mark - 读取特征返回信息
-(void)peripheral:(CBPeripheral *)peripheral didUpdateValueForCharacteristic:(CBCharacteristic *)characteristic error:(NSError *)error{
    NSData * data = characteristic.value;
    
    NSString *hexString = [data convertDataToHexStr];
    NSString *tagString = [hexString subStringWithRangeForNil:NSMakeRange(0, 2)];
    if (![tagString isEqualToString:@"f2"]) {
            NSLog(@"设备返回的数据:%@\n%@",data,[data convertDataToHexStr]);

    }
    if ([tagString isEqualToString:@"c4"]) {
        // 密码正确 c4232300010000  黄  白  是否爆闪(0:非爆闪  1-3爆闪)
        [self showHUDWith:NSLocalizedString(@"passwordSuccess", @"密码配对成功")];
        UIView *view = [[NSObject mainWindow]viewWithTag:8888];
        UIView *view1 = [[NSObject mainWindow]viewWithTag:9999];
        if (view) {
            [view removeFromSuperview];
        }
        if (view1) {
            [view1 removeFromSuperview];
        }
        if ([peripheral isEqual:self.leftPeripheral]) {
            self.homeView.topLeftButton.selected = NO;
            self.canWriteLeftCommand = YES;
            [self saveLeftPeripheralWithName:peripheral.name];
            [self saveLeftPeripheralWithPassword:self.leftPassword];
        }
        
        if ([peripheral isEqual:self.rightPeripheral]) {
            self.homeView.topRightButton.selected = NO;
            self.canWriteRightCommand = YES;
            [self saveRightPeripheralWithName:peripheral.name];
            [self saveRightPeripheralWithPassword:self.rightPassword];
        }
        
        if (self.connectPeripheralArray.count == 2) {
            [self sendCTCommand:peripheral];
        }else {
            NSString *hexWhite= [hexString subStringWithRangeForNil:NSMakeRange(2, 2)];
            NSString *hexYellow = [hexString subStringWithRangeForNil:NSMakeRange(4, 2)];
            NSString *hexBao = [hexString subStringWithRangeForNil:NSMakeRange(6, 2)];
            NSString *versionBig = [hexString subStringWithRangeForNil:NSMakeRange(8, 2)];
            NSString *versionSmall = [hexString subStringWithRangeForNil:NSMakeRange(10, 2)];
            
            
            self.model.hexYellow = hexYellow;
            self.model.hexWhite = hexWhite;
            self.model.bao = hexBao;
            self.model.versionBig = versionBig;
            self.model.verisonSmall = versionSmall;
            self.model.bright = [hexYellow ConvertedHexAdecimalStringToDecimalString].integerValue +[hexWhite ConvertedHexAdecimalStringToDecimalString].integerValue;
            [self updateHomeViewData];
        }
        
        NSString *temString = [hexString subStringWithRangeForNil:NSMakeRange(2, 4)];
        if ([temString isEqualToString:@"ff00"]) {
            self.homeView.firstButton.selected = YES;
            self.homeView.secondButton.selected = NO;
            self.homeView.thirdButton.selected = NO;
            self.homeView.fifBUtton.selected = NO;
            self.homeView.fourButton.selected = NO;

            
            
        }else if ([temString isEqualToString:@"8080"]) {
            self.homeView.firstButton.selected = NO;
            self.homeView.secondButton.selected = YES;
            self.homeView.thirdButton.selected = NO;
            self.homeView.fifBUtton.selected = NO;
            self.homeView.fourButton.selected = NO;

            
        }else if ([temString isEqualToString:@"00ff"]) {
            self.homeView.firstButton.selected = NO;
            self.homeView.secondButton.selected = NO;
            self.homeView.thirdButton.selected = YES;
            self.homeView.fifBUtton.selected = NO;
            self.homeView.fourButton.selected = NO;

            
        }else if ([temString isEqualToString:@"3300"]) {
            self.homeView.firstButton.selected = NO;
            self.homeView.secondButton.selected = NO;
            self.homeView.thirdButton.selected = NO;
            self.homeView.fifBUtton.selected = YES;
            self.homeView.fourButton.selected = NO;

            
        }else {
            self.homeView.firstButton.selected = NO;
            self.homeView.secondButton.selected = NO;
            self.homeView.thirdButton.selected = NO;
            self.homeView.fifBUtton.selected = NO;
        }

    }
    
    if ([tagString isEqualToString:@"c5"]) {
        // 密码错误
        if ([peripheral isEqual:self.leftPeripheral]) {
            [self sendCommandWith:self.leftPeripheral withCharacteristic:self.leftCharacteristic withCommand:@"C600000000000000000"];

            UIButton *sender = [[UIButton alloc]initWithFrame:[NSObject mainWindow].bounds];
            sender.backgroundColor = UIAlphaColorFromHex(0x000000, 0.2);
            sender.tag = 9999;
            [sender handleEven:UIControlEventTouchUpInside block:^(UIButton * _Nonnull sender) {
                UIView *view = [[NSObject mainWindow]viewWithTag:8888];
                if (view) {
                    [view removeFromSuperview];
                }
                [sender removeFromSuperview];
            }];
            [[NSObject mainWindow]addSubview:sender];
            
            PasswordView *pdView = [[PasswordView alloc] initWithFrame:CGRectMake(40, 200, ScreenWidth-80, 120)];
            pdView.title =  WWNSLocalizedString(@"changePasswordTips", @"智能灯控");
            pdView.tag = 8888;
            pdView.returnPasswordStringBlock = ^(NSString *password){
                // TODO:这里可以对输入的密码进行处理
                NSLog(@"%@",password);
                self.leftPassword = password;
                NSString *hexString = @"";
                for (NSInteger i = 0; i < password.length; i ++) {
                    NSString *temp = [password substringWithRange:NSMakeRange(i, 1)];
                    hexString = [NSString stringWithFormat:@"%@%@",hexString,[temp ConvertedDecimalStringToHexdecimalString]];
                }
                NSString *string = [NSString stringWithFormat:@"C4%@",hexString];
                NSData *data = [string convertHexStrToData];
                [self.leftPeripheral writeValue:data forCharacteristic:self.leftCharacteristic type:CBCharacteristicWriteWithResponse];
                UIView *view = [[NSObject mainWindow]viewWithTag:8888];
                UIView *view1 = [[NSObject mainWindow]viewWithTag:9999];
                if (view) {
                    [view removeFromSuperview];
                }
                if (view1) {
                    [view1 removeFromSuperview];
                }
                
            };
            [[NSObject mainWindow] addSubview:pdView];
//            [self showHUDWith:@"左灯密码输入错误"];
        }else {
//            [self showHUDWith:@"右灯密码输入错误"];
            [self sendCommandWith:self.rightPeripheral withCharacteristic:self.rightCharacteristic withCommand:@"C600000000000000000"];

            UIButton *sender = [[UIButton alloc]initWithFrame:[NSObject mainWindow].bounds];
            sender.backgroundColor = UIAlphaColorFromHex(0x000000, 0.2);
            sender.tag = 9999;
            [sender handleEven:UIControlEventTouchUpInside block:^(UIButton * _Nonnull sender) {
                UIView *view = [[NSObject mainWindow]viewWithTag:8888];
                if (view) {
                    [view removeFromSuperview];
                }
                [sender removeFromSuperview];
            }];
            [[NSObject mainWindow]addSubview:sender];
            
            PasswordView *pdView = [[PasswordView alloc] initWithFrame:CGRectMake(40, 200, ScreenWidth-80, 120)];
            pdView.tag = 8888;
            pdView.title =  WWNSLocalizedString(@"changePasswordTips", @"智能灯控");

            pdView.returnPasswordStringBlock = ^(NSString *password){
                // TODO:这里可以对输入的密码进行处理
                NSLog(@"%@",password);
                self.rightPassword = password;
                NSString *hexString = @"";
                for (NSInteger i = 0; i < password.length; i ++) {
                    NSString *temp = [password substringWithRange:NSMakeRange(i, 1)];
                    hexString = [NSString stringWithFormat:@"%@%@",hexString,[temp ConvertedDecimalStringToHexdecimalString]];
                }
                NSString *string = [NSString stringWithFormat:@"C4%@",hexString];
                NSData *data = [string convertHexStrToData];
                [self.rightPeripheral writeValue:data forCharacteristic:self.rightCharacteristic type:CBCharacteristicWriteWithResponse];
                UIView *view = [[NSObject mainWindow]viewWithTag:8888];
                UIView *view1 = [[NSObject mainWindow]viewWithTag:9999];
                if (view) {
                    [view removeFromSuperview];
                }
                if (view1) {
                    [view1 removeFromSuperview];
                }
                
            };
            [[NSObject mainWindow] addSubview:pdView];

        }
    }
    
    if ([tagString isEqualToString:@"a0"]) {
        // 密码正确 c4232300010000  黄  白  是否爆闪(0:非爆闪  1-3爆闪)
        if (!self.isUpdateAction) {
            return;
        }
        NSString *hexWhite = [hexString subStringWithRangeForNil:NSMakeRange(2, 2)];
        NSString *hexYellow = [hexString subStringWithRangeForNil:NSMakeRange(4, 2)];
//        NSString *hexBao = [hexString subStringWithRangeForNil:NSMakeRange(6, 2)];
        NSString *versionBig = [hexString subStringWithRangeForNil:NSMakeRange(8, 2)];
        NSString *versionSmall = [hexString subStringWithRangeForNil:NSMakeRange(10, 2)];
        
        
        
        self.model.hexYellow = hexYellow;
        self.model.hexWhite = hexWhite;
        self.model.versionBig = versionBig;
        self.model.verisonSmall = versionSmall;
        // TODO:需要学习的打开
  /*
        if (self.isLearn) {
            self.homeView.fourButton.selected = YES;
            [self.learnTimer invalidate];
            self.learnTimer = nil;
            
            self.learnTimer = [NSTimer scheduledTimerWithTimeInterval:2 repeats:NO block:^(NSTimer * _Nonnull timer) {
                self.isLearn = NO;
                self.homeView.fourButton.selected = NO;
                if ([peripheral isEqual:self.leftPeripheral]) {
                    [self saveLeftPeripheralWithData:[NSString stringWithFormat:@"%@%@",hexWhite,hexYellow]];
                }
                
                if ([peripheral isEqual:self.rightPeripheral]) {
                    [self saveRightPeripheralWithData:[NSString stringWithFormat:@"%@%@",hexYellow,hexWhite]];
                }
            }];
        }
   */
//        self.model.bao = hexBao;
//        self.model.versionBig = versionBig;
//        self.model.verisonSmall = versionSmall;
        self.model.bright = [hexYellow ConvertedHexAdecimalStringToDecimalString].integerValue +[hexWhite ConvertedHexAdecimalStringToDecimalString].integerValue;
        [self updateHomeViewData];
        
        NSString *temString = [hexString subStringWithRangeForNil:NSMakeRange(2, 4)];
        if ([temString isEqualToString:@"d000"]) {
            self.sceneView.selectIndex = 3;
            self.sceneView.selectTopIndex = 100;

        }else if ([temString isEqualToString:@"ff00"]) {
            self.sceneView.selectIndex = 4;
            self.sceneView.selectTopIndex = 100;
            

        }else if ([temString isEqualToString:@"e51a"]) {
            self.sceneView.selectIndex = 5;
            self.sceneView.selectTopIndex = 100;

        }else if ([temString isEqualToString:@"cc33"]) {
            self.sceneView.selectIndex = 6;
            self.sceneView.selectTopIndex = 100;

        }else if ([temString isEqualToString:@"b24d"]) {
            self.sceneView.selectIndex = 7;
            self.sceneView.selectTopIndex = 100;

        }else if ([temString isEqualToString:@"9966"]) {
            self.sceneView.selectIndex = 8;
            self.sceneView.selectTopIndex = 100;

        }else if ([temString isEqualToString:@"7f7f"]) {
            self.sceneView.selectIndex = 9;
            self.sceneView.selectTopIndex = 100;

        }else if ([temString isEqualToString:@"6699"]) {
            self.sceneView.selectIndex = 10;
            self.sceneView.selectTopIndex = 100;

        }else if ([temString isEqualToString:@"4db2"]) {
            self.sceneView.selectIndex = 11;
            self.sceneView.selectTopIndex = 100;

        }else if ([temString isEqualToString:@"33cc"]) {
            self.sceneView.selectIndex = 12;
            self.sceneView.selectTopIndex = 100;

        }else if ([temString isEqualToString:@"1ae5"]) {
            self.sceneView.selectIndex = 13;
            self.sceneView.selectTopIndex = 100;

        }else if ([temString isEqualToString:@"00ff"]) {
            self.sceneView.selectIndex = 14;
            self.sceneView.selectTopIndex = 100;

        }
        
        if ([temString isEqualToString:@"ff00"]) {
            self.homeView.firstButton.selected = YES;
            self.homeView.secondButton.selected = NO;
            self.homeView.thirdButton.selected = NO;
            self.homeView.fifBUtton.selected = NO;
            self.homeView.fourButton.selected = NO;

            
        }else if ([temString isEqualToString:@"8080"]) {
            self.homeView.firstButton.selected = NO;
            self.homeView.secondButton.selected = YES;
            self.homeView.thirdButton.selected = NO;
            self.homeView.fifBUtton.selected = NO;
            self.homeView.fourButton.selected = NO;

            
        }else if ([temString isEqualToString:@"00ff"]) {
            self.homeView.firstButton.selected = NO;
            self.homeView.secondButton.selected = NO;
            self.homeView.thirdButton.selected = YES;
            self.homeView.fifBUtton.selected = NO;
            self.homeView.fourButton.selected = NO;

            
        }else if ([temString isEqualToString:@"3300"]) {
            self.homeView.firstButton.selected = NO;
            self.homeView.secondButton.selected = NO;
            self.homeView.thirdButton.selected = NO;
            self.homeView.fifBUtton.selected = YES;
            self.homeView.fourButton.selected = NO;

            
        }else {
            self.homeView.firstButton.selected = NO;
            self.homeView.secondButton.selected = NO;
            self.homeView.thirdButton.selected = NO;
            self.homeView.fifBUtton.selected = NO;
//            self.homeView.fourButton.selected = NO;

        }
        
//        if (temString iseq) {
//            <#statements#>
//        }
//        [self sendCommandWith:peripheral withCharacteristic:characteristic withCommand:@"a2000000000000"];

    }
    
    if ([tagString isEqualToString:@"a9"]) {
        NSString *hexWhite = [hexString subStringWithRangeForNil:NSMakeRange(2, 2)];
        NSString *hexYellow = [hexString subStringWithRangeForNil:NSMakeRange(4, 2)];
        //        NSString *hexBao = [hexString subStringWithRangeForNil:NSMakeRange(6, 2)];
        //        NSString *versionBig = [hexString subStringWithRangeForNil:NSMakeRange(8, 2)];
        //        NSString *versionSmall = [hexString subStringWithRangeForNil:NSMakeRange(10, 2)];
        
        
        
        self.model.hexYellow = hexYellow;
        self.model.hexWhite = hexWhite;
        
        if (self.isLearn) {
            self.homeView.fourButton.selected = YES;
            [self.learnTimer invalidate];
            self.learnTimer = nil;
            
            self.learnTimer = [NSTimer scheduledTimerWithTimeInterval:2 repeats:NO block:^(NSTimer * _Nonnull timer) {
                self.isLearn = NO;
                self.homeView.fourButton.selected = NO;
                if ([peripheral isEqual:self.leftPeripheral]) {
                    [self saveLeftPeripheralWithData:[NSString stringWithFormat:@"%@%@",hexWhite,hexYellow]];
                }
                
                if ([peripheral isEqual:self.rightPeripheral]) {
                    [self saveRightPeripheralWithData:[NSString stringWithFormat:@"%@%@",hexYellow,hexWhite]];
                }
            }];
        }
        //        self.model.bao = hexBao;
        //        self.model.versionBig = versionBig;
        //        self.model.verisonSmall = versionSmall;
        self.model.bright = [hexYellow ConvertedHexAdecimalStringToDecimalString].integerValue +[hexWhite ConvertedHexAdecimalStringToDecimalString].integerValue;
        [self updateHomeViewData];
        
        NSString *temString = [hexString subStringWithRangeForNil:NSMakeRange(2, 4)];
        if ([temString isEqualToString:@"3300"]) {
            self.homeView.firstButton.selected = NO;
            self.homeView.secondButton.selected = NO;
            self.homeView.thirdButton.selected = NO;
            self.homeView.fifBUtton.selected = YES;
            
        }
    }
    
    if ([tagString isEqualToString:@"a2"]) {
        // 密码正确 c4232300010000  黄  白  是否爆闪(0:非爆闪  1-3爆闪)
        /*
        
        名      白       黄      亮度           图片default        图片select
        晴天     100%    0       20%
        夜间     100%    0       100%
        多云     90%    10       100%
        小雨     80%    20       100%
        中雨     100%   30       100%
        大雨     100%   40       100%
        小雪     100%   50       100%
        中雪     100%   60       100%
        大雪     100%   70       100%
        雷雨     100%   80       100%
        小雾     100%   90       100%
        大雾     100%   100       100%
         
         @[@{@"name":@"爆闪",@"white":@"100",@"yellow":@"100",@"bright":@"100",@"default":@"scene_001_default",@"select":@"scene_001_click",@"command":@"010000000000"}, @{@"name":@"渐变",@"white":@"100",@"yellow":@"100",@"bright":@"100",@"default":@"scene_0001_default",@"select":@"scene_0001_click",@"command":@"020000000000"},    @{@"name":@"慢闪",@"white":@"100",@"yellow":@"100",@"bright":@"100",@"default":@"scene_00001_default",@"select":@"scene_00001_click",@"command":@"030000000000"}, @{@"name":@"晴天",@"white":@"100",@"yellow":@"0",@"bright":@"20",@"default":@"scene_01_default",@"select":@"scene_01_click",@"command":@"330014000000"},    @{@"name":@"夜间",@"white":@"100",@"yellow":@"0",@"bright":@"100",@"default":@"scene_02_default",@"select":@"scene_02_click",@"command":@"ff0064000000"},    @{@"name":@"多云",@"white":@"90",@"yellow":@"10",@"bright":@"100",@"default":@"scene_03_default",@"select":@"scene_03_click",@"command":@"e51a64000000"},    @{@"name":@"小雨",@"white":@"80",@"yellow":@"20",@"bright":@"100",@"default":@"scene_04_default",@"select":@"scene_04_click",@"command":@"cc3364000000"},    @{@"name":@"中雨",@"white":@"70",@"yellow":@"30",@"bright":@"100",@"default":@"scene_05_default",@"select":@"scene_05_click",@"command":@"b24d64000000"},    @{@"name":@"大雨",@"white":@"60",@"yellow":@"50",@"bright":@"100",@"default":@"scene_06_default",@"select":@"scene_06_click",@"command":@"996664000000"},    @{@"name":@"小雪",@"white":@"50",@"yellow":@"50",@"bright":@"100",@"default":@"scene_07_default",@"select":@"scene_07_click",@"command":@"7f7f64000000"},    @{@"name":@"中雪",@"white":@"40",@"yellow":@"60",@"bright":@"100",@"default":@"scene_08_default",@"select":@"scene_08_click",@"command":@"669964000000"},    @{@"name":@"大雪",@"white":@"30",@"yellow":@"70",@"bright":@"100",@"default":@"scene_09_default",@"select":@"scene_09_click",@"command":@"4db264000000"},    @{@"name":@"雷雨",@"white":@"20",@"yellow":@"80",@"bright":@"100",@"default":@"scene_10_default",@"select":@"scene_10_click",@"command":@"33cc64000000"},    @{@"name":@"小雾",@"white":@"10",@"yellow":@"90",@"bright":@"100",@"default":@"scene_11_default",@"select":@"scene_11_click",@"command":@"1ae564000000"},    @{@"name":@"大雾",@"white":@"0",@"yellow":@"100",@"bright":@"100",@"default":@"scene_12_default",@"select":@"scene_12_click",@"command":@"00ff64000000"}


        **/
        NSString *hexWhite = [hexString subStringWithRangeForNil:NSMakeRange(2, 2)];
        NSString *hexYellow = [hexString subStringWithRangeForNil:NSMakeRange(4, 2)];
        NSString *hexBao = [hexString subStringWithRangeForNil:NSMakeRange(6, 2)];
        NSString *versionBig = [hexString subStringWithRangeForNil:NSMakeRange(8, 2)];
        NSString *versionSmall = [hexString subStringWithRangeForNil:NSMakeRange(10, 2)];
        
        NSString *temString = [hexString subStringWithRangeForNil:NSMakeRange(2, 4)];
        
//        if ([hexBao isEqualToString:@"01"]) {
//            self.sceneView.selectTopIndex = 0;
//        }else if ([hexBao isEqualToString:@"02"]) {
//            self.sceneView.selectTopIndex = 1;
//
//        }else if ([hexBao isEqualToString:@"03"]) {
//            self.sceneView.selectTopIndex = 2;
//
//        }else {
//
//
//        }
        
        
        
        
        
        self.model.hexYellow = hexYellow;
        self.model.hexWhite = hexWhite;
        self.model.bao = hexBao;
        self.model.versionBig = versionBig;
        self.model.verisonSmall = versionSmall;
        self.model.bright = [hexYellow ConvertedHexAdecimalStringToDecimalString].integerValue +[hexWhite ConvertedHexAdecimalStringToDecimalString].integerValue;
        [self updateHomeViewData];

    }
    
    if ([tagString isEqualToString:@"a3"] || [tagString isEqualToString:@"A3"]) {
        NSString *temp = [hexString subStringWithRangeForNil:NSMakeRange(2, 2)];
        if ([temp isEqualToString:@"01"]) {
            self.sceneView.selectTopIndex = 0;
            self.sceneView.selectIndex = 100;
        }else if ([temp isEqualToString:@"02"]) {
            self.sceneView.selectTopIndex = 1;
            self.sceneView.selectIndex = 100;

            
        }else if ([temp isEqualToString:@"03"]) {
            self.sceneView.selectTopIndex = 2;
            self.sceneView.selectIndex = 100;

            
        }
        
    }
    
    if ([tagString isEqualToString:@"f2"]) {
        NSString *command = @"5a000000000000";
        for (CBPeripheral *per in self.connectPeripheralArray) {
            if ([per isEqual:self.leftPeripheral]) {
                [self sendCommandWith:self.leftPeripheral withCharacteristic:self.leftCharacteristic withCommand:command];

            }
            if ([per isEqual:self.rightPeripheral]) {
                [self sendCommandWith:self.rightPeripheral withCharacteristic:self.rightCharacteristic withCommand:command];

            }
        }
    }
    
    if ([tagString isEqualToString:@"c0"]) {
        if ([peripheral isEqual:self.leftPeripheral]) {
            [self showHUDWith:@"左灯修改密码成功"];
            [self saveLeftPeripheralWithPassword:self.leftPassword];
        }else {
            [self showHUDWith:@"右灯修改密码成功"];
            [self saveRightPeripheralWithPassword:self.rightPassword];

        }
    }
    
    
    
    if ([tagString isEqualToString:@"c6"]) {
        NSLog(@"密码:%@",hexString);
    }
    
    
    
}

- (void)sendCommandWith:(CBPeripheral *)peripheral withCharacteristic:(CBCharacteristic *)cha withCommand:(NSString *)hexString {
    
    if (peripheral.state == CBPeripheralStateConnected) {
        if (cha != nil) {
            
            if ([peripheral isEqual:self.leftPeripheral] ) {
                // 展示密码框
                if (self.canWriteLeftCommand == NO) {
                    UIButton *sender = [[UIButton alloc]initWithFrame:[NSObject mainWindow].bounds];
                    sender.backgroundColor = UIAlphaColorFromHex(0x000000, 0.2);
                    sender.tag = 9999;
                    [sender handleEven:UIControlEventTouchUpInside block:^(UIButton * _Nonnull sender) {
                        UIView *view = [[NSObject mainWindow]viewWithTag:8888];
                        if (view) {
                            [view removeFromSuperview];
                        }
                        [sender removeFromSuperview];
                    }];
                    [[NSObject mainWindow]addSubview:sender];
                    
                    PasswordView *pdView = [[PasswordView alloc] initWithFrame:CGRectMake(40, 200, ScreenWidth-80, 120)];
                    pdView.title = WWNSLocalizedString(@"changePasswordTips", @"智能灯控");
                    pdView.tag = 8888;
                    pdView.returnPasswordStringBlock = ^(NSString *password){
                        // TODO:这里可以对输入的密码进行处理
                        NSLog(@"%@",password);
                        self.leftPassword = password;
                        NSString *hexString = @"";
                        for (NSInteger i = 0; i < password.length; i ++) {
                            NSString *temp = [password substringWithRange:NSMakeRange(i, 1)];
                            hexString = [NSString stringWithFormat:@"%@%@",hexString,[temp ConvertedDecimalStringToHexdecimalString]];
                        }
                        NSString *string = [NSString stringWithFormat:@"C4%@",hexString];
                        NSData *data = [string convertHexStrToData];
                        [self.leftPeripheral writeValue:data forCharacteristic:self.leftCharacteristic type:CBCharacteristicWriteWithResponse];
                        UIView *view = [[NSObject mainWindow]viewWithTag:8888];
                        UIView *view1 = [[NSObject mainWindow]viewWithTag:9999];
                        if (view) {
                            [view removeFromSuperview];
                        }
                        if (view1) {
                            [view1 removeFromSuperview];
                        }
                        
                    };
                    [[NSObject mainWindow] addSubview:pdView];
                }else {
                    [peripheral writeValue:[hexString convertHexStrToData] forCharacteristic:cha type:CBCharacteristicWriteWithResponse];

                }
                
            }
            
            if ([peripheral isEqual:self.rightPeripheral] ) {
                // 展示密码框
                if (self.canWriteRightCommand == NO) {
                    UIButton *sender = [[UIButton alloc]initWithFrame:[NSObject mainWindow].bounds];
                    sender.backgroundColor = UIAlphaColorFromHex(0x000000, 0.2);
                    sender.tag = 9999;
                    [sender handleEven:UIControlEventTouchUpInside block:^(UIButton * _Nonnull sender) {
                        UIView *view = [[NSObject mainWindow]viewWithTag:8888];
                        if (view) {
                            [view removeFromSuperview];
                        }
                        [sender removeFromSuperview];
                    }];
                    [[NSObject mainWindow]addSubview:sender];
                    
                    PasswordView *pdView = [[PasswordView alloc] initWithFrame:CGRectMake(40, 200, ScreenWidth-80, 120)];
                    pdView.title =  WWNSLocalizedString(@"changePasswordTips", @"智能灯控");

                    pdView.tag = 8888;
                    pdView.returnPasswordStringBlock = ^(NSString *password){
                        // TODO:这里可以对输入的密码进行处理
                        NSLog(@"%@",password);
                        self.rightPassword = password;
                        NSString *hexString = @"";
                        for (NSInteger i = 0; i < password.length; i ++) {
                            NSString *temp = [password substringWithRange:NSMakeRange(i, 1)];
                            hexString = [NSString stringWithFormat:@"%@%@",hexString,[temp ConvertedDecimalStringToHexdecimalString]];
                        }
                        NSString *string = [NSString stringWithFormat:@"C4%@",hexString];
                        NSData *data = [string convertHexStrToData];
                        [self.rightPeripheral writeValue:data forCharacteristic:self.rightCharacteristic type:CBCharacteristicWriteWithResponse];
                        UIView *view = [[NSObject mainWindow]viewWithTag:8888];
                        UIView *view1 = [[NSObject mainWindow]viewWithTag:9999];
                        if (view) {
                            [view removeFromSuperview];
                        }
                        if (view1) {
                            [view1 removeFromSuperview];
                        }
                        
                    };
                    [[NSObject mainWindow] addSubview:pdView];
                }else {
                    [peripheral writeValue:[hexString convertHexStrToData] forCharacteristic:cha type:CBCharacteristicWriteWithResponse];

                    
                }
                
            }
            

        }

    }
}

//- (void)judePeripheralAction:(CBPeripheral *)peripheral

- (void)updateHomeViewData {
    
    CGFloat white = [self.model.hexWhite ConvertedHexAdecimalStringToDecimalString].floatValue;
    CGFloat yellow = [self.model.hexYellow ConvertedHexAdecimalStringToDecimalString].floatValue;

    CGFloat angle = yellow /(yellow+white) *2.0 *M_PI;
    CGFloat temp = 0.02;
    if (white + yellow < 25.0) {
        self.homeView.circleView.angle = M_PI;
        self.homeView.sliderView.value = 0;
        
    }else {
        if (self.isControlType == 1) {
//            self.homeView.circleView.angle = 2.0 *M_PI-angle;
//            if (self.homeView.circleView.angle == 0) {
//                self.homeView.circleView.angle = temp;
//            }
//            
//            if (self.homeView.circleView.angle == 2.0 *M_PI) {
//                self.homeView.circleView.angle = 2.0 *M_PI-0.01;
//            }
        }else if (self.isControlType == 2) {
//            self.homeView.sliderView.value = (white + yellow -25.0)/230.0;

        }else {
            
            self.homeView.circleView.angle = 2.0 *M_PI-angle;
            
            if ((white + yellow -25.0)/230.0 < 0) {
                self.homeView.sliderView.value = 0;
            }else if ((white + yellow -25.0)/230.0 > 1) {
                self.homeView.sliderView.value = 1;

            }else {
                self.homeView.sliderView.value = (white + yellow -25.0)/230.0;

            }

            
            
            if (self.homeView.circleView.angle == 0) {
                self.homeView.circleView.angle = temp;
            }
            
            if (self.homeView.circleView.angle == 2.0 *M_PI) {
                self.homeView.circleView.angle = 2.0 *M_PI-0.01;
            }

        }
        
    }
    
    
    
}

- (void)sendCTCommand:(CBPeripheral *)peripheral {
    
    NSLog(@"%f\n%f",self.homeView.circleView.angle,self.homeView.sliderView.value);
    
    CGFloat bright = 230.0 *self.homeView.sliderView.value+ 25;
    NSInteger white = bright *self.homeView.circleView.angle/2.0/M_PI;
    NSInteger yellow = bright - white;
    NSInteger birghtPrecent = bright/255.0 *100;
    
    NSString *whiteString = [NSString stringWithFormat:@"%ld",white];
    NSString *yellowString = [NSString stringWithFormat:@"%ld",yellow];
    NSString *brightString = [NSString stringWithFormat:@"%ld",birghtPrecent];
    
    NSString *commandString = [NSString stringWithFormat:@"a0%@%@%@000000",[whiteString ConvertedDecimalStringToHexdecimalString],[yellowString ConvertedDecimalStringToHexdecimalString],[brightString ConvertedDecimalStringToHexdecimalString]];
    NSLog(@"发送的%@",commandString);
    if ([peripheral isEqual:self.leftPeripheral]) {
        [self sendCommandWith:self.leftPeripheral withCharacteristic:self.leftCharacteristic withCommand:commandString];
        
    }
    if ([peripheral isEqual:self.rightPeripheral]) {
        [self sendCommandWith:self.rightPeripheral withCharacteristic:self.rightCharacteristic withCommand:commandString];
        
    }
    
    [self saveLeftPeripheralWithData:[NSString stringWithFormat:@"%@%@",[whiteString ConvertedDecimalStringToHexdecimalString],[yellowString ConvertedDecimalStringToHexdecimalString]]];
    [self saveRightPeripheralWithData:[NSString stringWithFormat:@"%@%@",[whiteString ConvertedDecimalStringToHexdecimalString],[yellowString ConvertedDecimalStringToHexdecimalString]]];

    
}


#pragma mark - HomeViewDelegate

- (void)HomeViewAutoButtonClicked {
    if (self.connectPeripheralArray.count < 1) {
        [self blueListViewShow];
        return;
    }
    UIWindow *window = [NSObject mainWindow];
    AutoAlertView *alertView = [[AutoAlertView alloc]initWithFrame:window.bounds];
    alertView.titleString = WWNSLocalizedString(@"autoTips", @"智能灯控");
    alertView.delegate = self;
    [window addSubview:alertView];
}

- (void)HomeViewTopLeftButtonClicked {
    [self blueListViewShow];
}

- (void)HomeViewTopRightButtonClicked {
    [self blueListViewShow];
}

-(void)HomeViewSlderViewAction:(CGFloat)value {
    if (self.connectPeripheralArray.count < 1) {
        [self blueListViewShow];
        return;
    }
    
    self.isUpdateAction = YES;
    self.isControlType = 2;
    for (CBPeripheral *peripheral in self.connectPeripheralArray) {
        if ([peripheral isEqual:self.leftPeripheral]) {
            [self sendCTCommand:self.leftPeripheral];
        }
        
        if ([peripheral isEqual:self.rightPeripheral]) {
            [self sendCTCommand:self.rightPeripheral];
        }
    }
    
    
}

- (void)HomeViewSlderViewMoveAction:(CGFloat)value {
    
    self.isLock = YES;
    if (self.connectPeripheralArray.count < 1) {
        [self blueListViewShow];
        return;
    }
    
    self.isUpdateAction = NO;
    self.isControlType = 2;

    for (CBPeripheral *peripheral in self.connectPeripheralArray) {
        if ([peripheral isEqual:self.leftPeripheral]) {
            [self sendCTCommand:self.leftPeripheral];
        }
        
        if ([peripheral isEqual:self.rightPeripheral]) {
            [self sendCTCommand:self.rightPeripheral];
        }
    }
    
    
}



- (void)HomeViewCircleAction:(CGFloat)value {
    if (self.connectPeripheralArray.count < 1) {
        [self blueListViewShow];
        return;
    }
//    self.homeView.fourButton.selected = NO;

    self.isUpdateAction = YES;
    self.isControlType = 1;

    for (CBPeripheral *peripheral in self.connectPeripheralArray) {
        if ([peripheral isEqual:self.leftPeripheral]) {
            [self sendCTCommand:self.leftPeripheral];
        }
        
        if ([peripheral isEqual:self.rightPeripheral]) {
            [self sendCTCommand:self.rightPeripheral];
        }
    }

}

- (void)HomeCircleViewCircleStartActionWith:(CGFloat)value {
    if (self.connectPeripheralArray.count < 1) {
        [self blueListViewShow];
        return;
    }
    self.homeView.fourButton.selected = YES;
}

- (void)HomeViewCircleMoveAction:(CGFloat)value {
    if (self.connectPeripheralArray.count < 1) {
        [self blueListViewShow];
        return;
    }
    self.isUpdateAction = NO;
    self.isControlType = 1;

    NSLog(@"---发了-----");
    for (CBPeripheral *peripheral in self.connectPeripheralArray) {
        if ([peripheral isEqual:self.leftPeripheral]) {
            [self sendCTCommand:self.leftPeripheral];
        }
        
        if ([peripheral isEqual:self.rightPeripheral]) {
            [self sendCTCommand:self.rightPeripheral];
        }
    }
    
}

- (void)HomeViewCloseLightAction {
    
    if (self.connectPeripheralArray.count < 1) {
        [self blueListViewShow];
        return;
    }
    
    self.isControlType = 0;
    
    NSString *command = @"a000000000000000";
    for (CBPeripheral *per in self.connectPeripheralArray) {
        if ([per isEqual:self.leftPeripheral]) {
            [self sendCommandWith:self.leftPeripheral withCharacteristic:self.leftCharacteristic withCommand:command];

        }
        if ([per isEqual:self.rightPeripheral]) {
            [self sendCommandWith:self.rightPeripheral withCharacteristic:self.rightCharacteristic withCommand:command];

        }
    }
    
}

- (void)HomeViewModelButtonClicked:(NSInteger)type {
    if (self.connectPeripheralArray.count < 1) {
        [self blueListViewShow];
        return;
    }
    self.isControlType = 0;

    if (type == 0) {
        NSString *command = [NSString stringWithFormat:@"a0%@%@%@000000",[@"255" ConvertedDecimalStringToHexdecimalString],[@"0" ConvertedDecimalStringToHexdecimalString],[@"100" ConvertedDecimalStringToHexdecimalString]];
        for (CBPeripheral *per in self.connectPeripheralArray) {
            if ([per isEqual:self.leftPeripheral]) {
                [self sendCommandWith:self.leftPeripheral withCharacteristic:self.leftCharacteristic withCommand:command];

            }
            if ([per isEqual:self.rightPeripheral]) {
                [self sendCommandWith:self.rightPeripheral withCharacteristic:self.rightCharacteristic withCommand:command];

            }
        }
    }else if (type == 1) {
        NSString *command = [NSString stringWithFormat:@"a0%@%@%@000000",[@"128" ConvertedDecimalStringToHexdecimalString],[@"128" ConvertedDecimalStringToHexdecimalString],[@"100" ConvertedDecimalStringToHexdecimalString]];
        for (CBPeripheral *per in self.connectPeripheralArray) {
            if ([per isEqual:self.leftPeripheral]) {
                [self sendCommandWith:self.leftPeripheral withCharacteristic:self.leftCharacteristic withCommand:command];

            }
            if ([per isEqual:self.rightPeripheral]) {
                [self sendCommandWith:self.rightPeripheral withCharacteristic:self.rightCharacteristic withCommand:command];

            }
        }
        
    }else if (type == 2) {
        NSString *command = [NSString stringWithFormat:@"a0%@%@%@000000",[@"0" ConvertedDecimalStringToHexdecimalString],[@"255" ConvertedDecimalStringToHexdecimalString],[@"100" ConvertedDecimalStringToHexdecimalString]];
        for (CBPeripheral *per in self.connectPeripheralArray) {
            if ([per isEqual:self.leftPeripheral]) {
                [self sendCommandWith:self.leftPeripheral withCharacteristic:self.leftCharacteristic withCommand:command];

            }
            if ([per isEqual:self.rightPeripheral]) {
                [self sendCommandWith:self.rightPeripheral withCharacteristic:self.rightCharacteristic withCommand:command];

            }
        }
        
    }else if (type == 3) {
        
        NSLog(@"%@\n%@",self.model.hexWhite,self.model.hexYellow);
        self.homeView.fourButton.selected = YES;
        NSString *leftData = [self getLeftPeripheralData];
        NSString *rightData = [self getRightPeripheralData];

        
        
        
//        [self saveLeftPeripheralWithData:[NSString stringWithFormat:@"%@%@",self.model.hexWhite,self.model.hexYellow]];
//        [self saveRightPeripheralWithData:[NSString stringWithFormat:@"%@%@",self.model.hexWhite,self.model.hexYellow]];
        
        NSString *command = [NSString stringWithFormat:@"a0%@00000000",leftData];
        for (CBPeripheral *per in self.connectPeripheralArray) {
            if ([per isEqual:self.leftPeripheral]) {
                if (leftData.length > 0) {
                    command = [NSString stringWithFormat:@"a0%@00000000",leftData];
                    [self sendCommandWith:self.leftPeripheral withCharacteristic:self.leftCharacteristic withCommand:command];
                }
                

            }
            if ([per isEqual:self.rightPeripheral]) {
                if (rightData.length > 0) {
                    command = [NSString stringWithFormat:@"a0%@00000000",rightData];
                    [self sendCommandWith:self.rightPeripheral withCharacteristic:self.rightCharacteristic withCommand:command];
                }
                

            }
        }
        
    }else if (type == 4) {
        
        NSString *string = [[NSUserDefaults standardUserDefaults]objectForKey:noLonger_show_key];
        if (![string isEqualToString:@"no"]) {
            [self addDayLightAlertViewAction];
        }
        NSString *command = [NSString stringWithFormat:@"a9%@%@%@000000",[@"51" ConvertedDecimalStringToHexdecimalString],[@"0" ConvertedDecimalStringToHexdecimalString],[@"20" ConvertedDecimalStringToHexdecimalString]];
        NSLog(@"%@",command);
        for (CBPeripheral *per in self.connectPeripheralArray) {
            if ([per isEqual:self.leftPeripheral]) {
                [self sendCommandWith:self.leftPeripheral withCharacteristic:self.leftCharacteristic withCommand:command];

            }
            if ([per isEqual:self.rightPeripheral]) {
                [self sendCommandWith:self.rightPeripheral withCharacteristic:self.rightCharacteristic withCommand:command];

            }
        }
        
    }
}

- (void)DayLightAlertViewIsSelected:(BOOL)isSelected {
    
    
}

#pragma mark - blueListViewDelegate

- (void)BlueToothListViewStartScan {
    
    [self.centerManager scanForPeripheralsWithServices:nil options:nil];
    
}

- (void)BlueToothListViewEndScan {
    
    [self.centerManager stopScan];
}

- (void)BlueToothListViewClose {
    [self.centerManager stopScan];
    self.blueView.hidden = YES;
}

- (void)BlueToothListViewClickPeripheral:(CBPeripheral *)peripheral {
//    self.isAutoConnected ++;
    
    if (self.connectPeripheralArray.count >= 2) {
//        [self showHUDWith:@"你已连接了两个设备,如需链接请先断开"];
        return;
    }
    [self.centerManager connectPeripheral:peripheral options:nil];
    
}

- (void)BlueToothListViewClickDisconnectPeripheral:(CBPeripheral *)peripheral {
    
//    self
    [self.centerManager cancelPeripheralConnection:peripheral];
    if ([peripheral isEqual:self.leftPeripheral]) {
        self.isAutoConnected = NO;
    }
    
    if ([peripheral isEqual:self.rightPeripheral]) {
        self.isAutoRightConnect = NO;
    }
}

#pragma mark - sceneDelegate

- (void)SceneViewSelectDic:(NSDictionary *)dic withIndex:(NSInteger)index {
    if (self.connectPeripheralArray.count < 1) {
        [self blueListViewShow];
        return;
    }
    self.isControlType = 0;

    NSString *bright = dic[@"bright"];
    NSString *white = dic[@"white"];
//    NSString *yellow = dic[@"yellow"];
    NSInteger brightValue = bright.floatValue /100.0 *255.0;
    NSInteger whiteValue = brightValue *white.floatValue /100.0;
    NSInteger yellowValue = brightValue - whiteValue;
//    NSInteger total = bright.floatValue /100.0 *255.0;
    
    NSString *brightString = [NSString stringWithFormat:@"%ld",brightValue];
    NSString *whiteString = [NSString stringWithFormat:@"%ld",whiteValue];
    NSString *yellowString = [NSString stringWithFormat:@"%ld",yellowValue];
    
    NSString *command = dic[@"command"];
    if (index < 3) {
        command = [NSString stringWithFormat:@"A3%@",command];
    }else {
        command = [NSString stringWithFormat:@"A0%@",command];

//        command = [NSString stringWithFormat:@"A0%@%@%@000000",[whiteString ConvertedDecimalStringToHexdecimalString],[yellowString ConvertedDecimalStringToHexdecimalString],[bright ConvertedDecimalStringToHexdecimalString]];
    }

    for (CBPeripheral *per in self.connectPeripheralArray) {
        if ([per isEqual:self.leftPeripheral]) {
            if ( index >= 3) {
//                [self sendCommandWith:self.leftPeripheral withCharacteristic:self.leftCharacteristic withCommand:@"a4000000000000"];

            }
            [self sendCommandWith:self.leftPeripheral withCharacteristic:self.leftCharacteristic withCommand:command];
            if (index < 3) {
                // a2000000000000
                [self sendCommandWith:self.leftPeripheral withCharacteristic:self.leftCharacteristic withCommand:@"a2000000000000"];
            }

        }
        if ([per isEqual:self.rightPeripheral]) {
            if ( index >= 3) {
//                [self sendCommandWith:self.rightPeripheral withCharacteristic:self.rightCharacteristic withCommand:@"a4000000000000"];

            }
            [self sendCommandWith:self.rightPeripheral withCharacteristic:self.rightCharacteristic withCommand:command];
            if (index < 3) {
                // a2000000000000
                [self sendCommandWith:self.rightPeripheral withCharacteristic:self.rightCharacteristic withCommand:@"a2000000000000"];
            }

        }
    }
    
}


#pragma mark - DropTableViewDelegate

- (void)DropTableViewPasswordAction:(NSString *)password {
    if (self.connectPeripheralArray.count < 1) {
        [self blueListViewShow];
        return;
    }
    NSString *hexString = @"";
    for (NSInteger i = 0; i < password.length; i ++) {
        NSString *temp = [password substringWithRange:NSMakeRange(i, 1)];
        hexString = [NSString stringWithFormat:@"%@%@",hexString,[temp ConvertedDecimalStringToHexdecimalString]];
    }
    NSString *string = [NSString stringWithFormat:@"C0%@",hexString];
//    NSData *data = [string convertHexStrToData];
    for (CBPeripheral *per in self.connectPeripheralArray) {
        if ([per isEqual:self.leftPeripheral]) {
            self.leftPassword = password;
            [self sendCommandWith:self.leftPeripheral withCharacteristic:self.leftCharacteristic withCommand:string];

        }
        if ([per isEqual:self.rightPeripheral]) {
            self.rightPassword = password;
            [self sendCommandWith:self.rightPeripheral withCharacteristic:self.rightCharacteristic withCommand:string];

        }
    }
    
}

- (void)DropTableViewSoftUpdateClick {
    if (self.connectPeripheralArray.count < 1) {
        [self blueListViewShow];
        return;
    }
    [self showHUDWith:@"暂没此功能"];
}

- (void)DropTableViewSystemVersionClick {
    if (self.connectPeripheralArray.count < 1) {
        [self blueListViewShow];
        return;
    }
    NSDictionary *infoDictionary = [[NSBundle mainBundle] infoDictionary];
    NSString *app_Version = [infoDictionary objectForKey:@"CFBundleShortVersionString"];
    NSString *bleVersion = @"";
    for (CBPeripheral *per in self.connectPeripheralArray) {
        bleVersion = [self.macDictionary objectForKey:per.name];
    }
    UIAlertController *alertVC = [UIAlertController alertControllerWithTitle:NSLocalizedString(@"currentVersion", @"当前版本号") message:[NSString stringWithFormat:@"APP Version:%@\n%@ Version:%@.%@\n%@ Version:%@.0",app_Version,NSLocalizedString(@"Device", @"设备"),[self.model.versionBig ConvertedHexAdecimalStringToDecimalString],[self.model.verisonSmall ConvertedHexAdecimalStringToDecimalString],NSLocalizedString(@"bluetooth", @""),[bleVersion ConvertedHexAdecimalStringToDecimalString]] preferredStyle:UIAlertControllerStyleAlert];
    
    UIAlertAction *action = [UIAlertAction actionWithTitle:NSLocalizedString(@"yes", @"当前版本号") style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
        
    }];
    [alertVC addAction:action];
    [self presentViewController:alertVC animated:YES completion:nil];
}

#pragma mark - autoAlertViewDelegate

- (void)AutoAlertViewComfirmButtonClicked {
    if (self.connectPeripheralArray.count < 1) {
        [self blueListViewShow];
        return;
    }
    [self fetchWeaTherApi];
}
    

#pragma mark - set && get

- (void)setIsHome:(BOOL)isHome {
    
    _isHome = isHome;
    if (isHome) {
        self.sceneView.hidden = YES;
        self.homeView.hidden = NO;
    }else {
        self.sceneView.hidden = NO;
        self.homeView.hidden = YES;
    }
    
    self.homeButton.selected = !isHome;
    
//    self.homeButton.selected = !isHome;
//    self.sceneButton.selected = !isHome;
}

- (NSMutableArray *)peripheralArray {
    
    if (!_peripheralArray) {
        _peripheralArray = [NSMutableArray array];
    }
    return _peripheralArray;
}

- (NSMutableArray *)connectPeripheralArray {
    
    if (!_connectPeripheralArray) {
        _connectPeripheralArray = [NSMutableArray array];
    }
    return _connectPeripheralArray;
}

- (NSMutableDictionary *)macDictionary {
    
    if (!_macDictionary) {
        _macDictionary = [NSMutableDictionary dictionary];
    }
    return _macDictionary;
}



@end
